package priv.jesse.mall.web.admin;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import priv.jesse.mall.entity.Classification;
import priv.jesse.mall.entity.Product;
import priv.jesse.mall.entity.ProductComment;
import priv.jesse.mall.entity.pojo.ResultBean;
import priv.jesse.mall.service.ClassificationService;
import priv.jesse.mall.service.ProductCommentService;
import priv.jesse.mall.service.ProductService;
import priv.jesse.mall.utils.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Controller
@RequestMapping("/admin/product")
public class AdminProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ClassificationService classificationService;

    @Autowired
    private ProductCommentService productCommentService;


    @RequestMapping("/toList.html")
    public String toList() {
        return "admin/product/list";
    }

    @RequestMapping("/toAdd.html")
    public String toAdd() {
        return "admin/product/add";
    }

    @RequestMapping("/toEdit.html")
    public String toEdit(int id, Map<String, Object> map,HttpServletRequest request) {
        Product product = productService.findById(id);
        Classification classification = classificationService.findById(product.getCsid());
        Classification classification1 = classificationService.findById(product.getCsid1());
        product.setCategorySec1(classification1);
        product.setCategorySec(classification);
        String[] list=product.getImage().split("&");

        String urlprefix = request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort();
        for(int i=0;i<list.length;i++){
            list[i]=urlprefix.trim()+"/mall/admin/product/getImg.do?url="+ list[i].replace("/","%2F").replace("\\","%2F");
        }
        product.setImagelist(list);
        map.put("product", product);
        return "admin/product/edit";
    }



    @RequestMapping("/toEditPingLun.html")
    public String toEditPingLun(int id, Map<String, Object> map,HttpServletRequest request) {
        Product product = productService.findById(id);
        map.put("product", product);
        return "admin/product/pinglun";
    }


    @ResponseBody
    @RequestMapping("/list.do")
    public ResultBean<List<Product>> listProduct(int pageindex,@RequestParam(value = "pageSize", defaultValue = "15") int pageSize,HttpServletRequest request) {
        Pageable pageable = new PageRequest(pageindex, pageSize, null);
        List<Product> list = productService.findAll(pageable).getContent();

        String urlprefix = request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort();
        for(int i=0;i<list.size();i++){
            String[] ss=list.get(i).getImage().split("&");
            String image=urlprefix.trim()+"/mall/admin/product/getImg.do?url="+ ss[0].replace("/","%2F").replace("\\","%2F");
            list.get(i).setImage(image);
        }
        return new ResultBean<>(list);
    }

    @ResponseBody
    @RequestMapping("/getTotal")
    public ResultBean<Integer> getTotal() {
        Pageable pageable = new PageRequest(1, 15, null);
        int total = (int) productService.findAll(pageable).getTotalElements();
        return new ResultBean<>(total);
    }

    @RequestMapping("/del.do")
    @ResponseBody
    public ResultBean<Boolean> del(int id) {
        productService.delById(id);
        return new ResultBean<>(true);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/add.do")
    public void add(String image,
                    String title,
                    Double marketPrice,
                    Double shopPrice,
                    int isHot,
                    String desc,
                    String paihang,
                    int csid1,
                    int csid,
                    int salesCount,
                    HttpServletRequest request,
                    HttpServletResponse response) throws Exception {
        Product product = new Product();
        product.setTitle(title);
        product.setPaihang(paihang);
        product.setMarketPrice(marketPrice);
        product.setShopPrice(shopPrice);
        product.setDesc(desc);
        product.setSalesCount(salesCount);
        product.setIsHot(isHot);
        product.setCsid1(csid1);
        product.setCsid(csid);
        product.setPdate(new Date());
        product.setImage(image);
        int id = productService.create(product);
        if (id <= 0) {
            request.setAttribute("message", "添加失败！");
            request.getRequestDispatcher("toAdd.html").forward(request, response);
        } else {
            request.getRequestDispatcher("toEdit.html?id=" + id).forward(request, response);
        }
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addimg.do")
    public ResultBean<String> addimg(HttpServletRequest request,MultipartFile[] file) throws Exception {
        String imgUrl="";
        if (file != null && file.length > 0) {
            for (int i = 0; i < file.length; i++) {
                MultipartFile filex = file[i];
                // 保存文件
                imgUrl = imgUrl+FileUtil.saveFile(filex) + "&";
            }
        }
        ResultBean<String> r = new ResultBean(imgUrl.toString());
        return r;
    }



    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/update.do")
    public ResultBean<String> update(int id,
                       String title,
                       String image,
                       Double marketPrice,
                       Double shopPrice,
                       String desc,
                       String paihang,
                       int csid,
                       int csid1,
                       int isHot,
                       int salesCount,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {
        Product product = productService.findById(id);
        product.setTitle(title);
        product.setPaihang(paihang);
        product.setMarketPrice(marketPrice);
        product.setShopPrice(shopPrice);
        product.setDesc(desc);
        product.setSalesCount(salesCount);
        product.setIsHot(isHot);
        product.setCsid1(csid1);
        product.setCsid(csid);
        product.setPdate(new Date());
        product.setImage(image);
        boolean flag = false;
        try {
            productService.update(product);
            flag = true;
        } catch (Exception e) {
            throw new Exception(e);
        }
        if (!flag) {
            ResultBean<String> r = new ResultBean("更新失败");
            return r;
        }
        ResultBean<String> r = new ResultBean("更新成功");
        return r;
    }


    @RequestMapping(method = RequestMethod.POST, value = "/updatepinglun.do")
    public void update(int id, String name,String desc,HttpServletRequest request, HttpServletResponse response) throws Exception {
        ProductComment productComment = new ProductComment();
        productComment.setProductId(id);
        productComment.setContent(desc);
        productComment.setName(name);
        try {
            productCommentService.create(productComment);
        } catch (Exception e) {
            throw new Exception(e);
        }
            request.getRequestDispatcher("toList.html").forward(request, response);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/img/{filename:.+}")
    public void getImage(@PathVariable(name = "filename", required = true) String filename,
                         HttpServletResponse res) throws IOException {
        File file = new File("file/" + filename);
        if (file != null && file.exists()) {
            res.setHeader("content-type", "application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            res.setContentLengthLong(file.length());
            Files.copy(Paths.get(file.toURI()), res.getOutputStream());
        }
    }


    @RequestMapping("/getImg.do")
    public String getimg(String url,HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
        FileInputStream fis = new FileInputStream(url);
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
        return null;
    }















}
